package com.linkage.jz.bankruptcy.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.text.Layout;
import android.text.Selection;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.TypedValue;

import com.linkage.jz.bankruptcy.utils.LogUtil;

/**
 * @author AFAP
 * 带计数的EditText
 */
public class CountEditText extends android.support.v7.widget.AppCompatEditText {

    String XML_NAMESPACE_ANDROID = "http://schemas.android.com/apk/res/android";
    private int mMaxLength = -1;


    public CountEditText(Context context) {
        super(context);
    }

    public CountEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        mMaxLength = attrs.getAttributeIntValue(XML_NAMESPACE_ANDROID, "maxLength", -1);
    }

    public CountEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mMaxLength = attrs.getAttributeIntValue(XML_NAMESPACE_ANDROID, "maxLength", -1);
    }


    public void setmMaxLength(int mMaxLength) {
        this.mMaxLength = mMaxLength;
    }

    boolean isInit = false;

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        float textSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 14, getResources().getDisplayMetrics());
        if (!isInit) { // 计数固定在下一行位置
            isInit = true;
            setPadding(getPaddingLeft(), getPaddingTop(), getPaddingRight(), (int) (getPaddingBottom() + textSize));
        }

//        // 光标当前位置
//        int currentLine = Selection.getSelectionStart(getText());
//        Layout layout = getLayout();
//
//        if (currentLine != -1 && layout != null) {
//            currentLine = layout.getLineForOffset(currentLine) + 1;
//        }
//        LogUtil.v("&&&&", "currentLine-->" + currentLine);


        TextPaint mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
        float marginRight = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, getResources().getDisplayMetrics());
        float marginBottom = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 6, getResources().getDisplayMetrics());

        mTextPaint.setTextSize(textSize);
        mTextPaint.setColor(Color.parseColor("#999999"));
        int width = getWidth();
        int height = getHeight();
        String text;
        if (mMaxLength > 0) {
            text = getEditableText().length() + "/" + mMaxLength;
        } else {
            text = getEditableText().length() + "";
        }
        float textWidth = mTextPaint.measureText(text);

        float x = width - textWidth - marginRight;
        float y = (float) (height -  marginBottom);

        canvas.drawText(text, x, y, mTextPaint);
    }
}
